package com.hcom.transaction.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.hc.entity.Order;
import com.hc.utils.RedisIDWoker;
import com.hc.utils.ResponseEntity;
import com.hc.utils.UtilClass;
import com.hcom.common.AliPayConfig;
import com.hcom.feignclient.GoodsStockDel;
import com.hcom.feignclient.OrderFeignClient;
import com.hcom.feignclient.PayRecord;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description：支付接口对接测试类
 * @Author：曹杰克
 * @CreateTime：2022/10/27 15:25
 */
//@RestController 不用原因是支付返回的是页面
@Controller
public class PayTestController {
    //网关https://openapi.alipaydev.com/gateway.do
    private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";
    @Resource
    private AliPayConfig aliPayConfig;
    @Resource
    GoodsStockDel goodsStockDel;
    @Resource
    PayRecord payRecord;
    @Resource
    OrderFeignClient orderFeignClient;

    //存放要展示再支付界面的信息
    @RequestMapping("/api/alipay")     //访问  内网穿透+地址        http://3ceyyp.natappfree.cc/api/alipay, @RequestBody AlipayVo alipayVo

    public void chongzhi(HttpServletResponse httpResponse) throws Exception {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        String id = "111";
        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        //发起展示支付界面的请求
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        JSONObject bizContent = new JSONObject();
        String replaceUUID = UUID.randomUUID().toString().replace("-", "");
//        long orderId = redisIDWoker.nextId(goods.getId() + "");
//        bizContent.set("out_trade_no", alipayVo.getOut_trade_no());  // 我们自己生成的订单编号 订单号不能重复
        bizContent.set("out_trade_no", replaceUUID);  // 我们自己生成的订单编号 订单号不能重复
//        bizContent.set("total_amount", alipayVo.getTotal_amount()); // 订单的总金额
        bizContent.set("total_amount", 50); // 订单的总金额
        bizContent.set("subject", "充值");   // 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());
        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("/alipay/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        System.out.println("saaa");
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // System.out.println("交易名称: " + params.get("subject"));
//                System.out.println("交易状态: " + params.get("trade_status"));
//                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
//                System.out.println("商户订单号: " + params.get("out_trade_no"));
//                System.out.println("交易金额: " + params.get("total_amount"));
//                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
//                System.out.println("买家付款时间: " + params.get("gmt_payment"));
//                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                //修改订单状态
                String trade_no = params.get("trade_no");
                Order order = new Order();
                order.setCode(trade_no);
                ResponseEntity responseEntity = orderFeignClient.selectByOrderCode(order);
                if(responseEntity.getData() != null){
                    order.setStatus("y");
                    //将订单修改为已支付
                    orderFeignClient.changeByOrderCode(order);
                    //减少库存
                    Order data = (Order) responseEntity.getData();
                    //对数据库进行操作,支付完成对数据库订单状态进行修改。
                    UtilClass utilClass = new UtilClass();
                    utilClass.setId(data.getGoodsId());
                    utilClass.setNum(data.getNum());
                    goodsStockDel.decstock(utilClass);
                }





            }
        }
        return "success";
    }
}

